package com.dhcc.bpm.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

public class ReadTextFile {
    private static final Logger log = LoggerFactory.getLogger(ReadTextFile.class);


    // 从文本文件中读取内容   
    public static String readfile(String path) {
        String filepath, read;
        String readStr = "";
        filepath = path;  // 得到文本文件的路径
        File file = new File(filepath);
        try (FileReader fileread = new FileReader(file);
             BufferedReader bufread = new BufferedReader(fileread);) {
            while ((read = bufread.readLine()) != null) {
                read = read + "\r\n";
                readStr = readStr + read;
            }
        } catch (Exception e) {
            log.error("读取文件失败：{}", e);
        }
        return readStr;  // 返回从文本文件中读取内容
    }

    // 向文本文件中写入内容   
    public static void writefile(String path, String content, boolean append) {
        String filepath, filecontent;
        boolean addStr = append;  // 通过这个对象来判断是否向文本文件中追加内容
        filepath = path;  // 得到文本文件的路径
        filecontent = content;  // 需要写入的内容
        File writefile = new File(path);
        if (writefile.exists() == false)  // 如果文本文件不存在则创建它
        {
            try {
                writefile.createNewFile();
            } catch (IOException e) {
                log.error("写入文件失败：{}", e);
            }
            writefile = new File(filepath);  // 重新实例化
        }
        try (FileWriter filewriter = new FileWriter(writefile, addStr);) {
            // 删除原有文件的内容   
            java.io.RandomAccessFile file = new java.io.RandomAccessFile(path, "rw");
            file.setLength(0);

            // 写入新的文件内容   
            filewriter.write(filecontent);
        } catch (Exception e) {
            log.error("写入文件失败：{}", e);
        }
    }

    public static void main(String[] args) throws Exception {
        ReadTextFile parse = new ReadTextFile();
        String filecontent = parse.readfile("D:/new/public/20220124093837096-5-in-jsontosoap.xml");
        parse.writefile("D:/new/public/test.xml", filecontent, true);

    }
}